"""
Name : oss_utils.py
Author  : Jackcongx
Time    : 2020/10/15 10:21
"""
import datetime
import io
import random
import string

import oss2
import requests
from django.conf import settings


class RunOSS:
    def __init__(self, filename=None, dirname=None):
        self.AccessKeyId = settings.OSS_AK
        self.AccessKeySecret = settings.OSS_SK
        self.Endpoint = settings.OSS_ENDPOINT
        self.BuckerName = settings.OSS_BUCKERNAME
        self.dirname = dirname
        self.filename = filename

    def getBucket(self):
        auth = oss2.Auth(self.AccessKeyId, self.AccessKeySecret)
        bucket = oss2.Bucket(auth, self.Endpoint, self.BuckerName)
        return bucket

    def uploadFIle(self, objectfile):
        bucket = self.getBucket()
        now = datetime.datetime.now()
        random_name = now.strftime("%Y%m%d%H%M%S") + ''.join([random.choice(string.digits) for _ in range(4)])
        objectname = self.dirname + random_name + "." + self.filename.split(".")[-1]
        f = objectfile.read()
        try:
            ret = bucket.put_object(objectname, f)
            link = "https://{}.oss-cn-beijing.aliyuncs.com/".format(self.BuckerName) + objectname
            return {'status': ret.status, 'pay_certificate': link, 'objectname': objectname}
        except Exception as e:
            return e

    def deleteFIle(self, objectname):
        bucket = self.getBucket()
        try:
            ret = bucket.delete_object(objectname)
            return {'status': ret.status}
        except Exception as e:
            return e

    def parser(self, img):
        bucket = self.getBucket()
        now = datetime.datetime.now()
        random_name = now.strftime("%Y%m%d%H%M%S") + ''.join([random.choice(string.digits) for _ in range(4)])
        objectname = self.dirname + random_name + "." + self.filename.split(".")[-1]
        try:
            ret = bucket.put_object(objectname, img.getvalue())
            link = "https://{}.oss-cn-beijing.aliyuncs.com/".format(self.BuckerName) + objectname
            return {'status': ret.status, 'pay_certificate': link, 'objectname': objectname}
        except Exception as e:
            return e

    def img_url_io(self, url):
        img = io.BytesIO(requests.get(url, timeout=300).content)
        statusCode = self.parser(img)
        try:
            if statusCode.get('status') == 200:
                return 1, statusCode.get('pay_certificate')
            else:
                return 0, '上传oss错误'
        except Exception as e:
            return 0, '上传oss错误'